import Taro, { Component } from '@tarojs/taro'
import { View, Text, Image} from '@tarojs/components'
import './toHome.scss'

// 引入数据
import data from '../../http/mock'

// 引入子组件
import Search from '../../component/search/search'
import TopBar from '../../component/index/topBar/index'

export default class ToHome extends Component {
  config = {
    navigationBarTitleText: '商品分类'
  }
  constructor (props) {
    super(props)
    this.state = {
      foodTypeList: '',
      foodList: '',
      activeType: '',
      height: process.env.TARO_ENV === 'h5' ? Taro.getSystemInfoSync().windowHeight : Taro.getSystemInfoSync().windowHeight +'px'
    }
  }
  componentWillMount () { }

  componentDidMount () {
    this.setState({
      foodTypeList: data.toHome.foodType
    }, () => {
      this.setState({
        activeType: this.state.foodTypeList[0].id,
        foodList: data.toHome.foodList[this.state.foodTypeList[0].id]
      })
    })
  }

  componentWillUnmount () { }

  componentDidShow () { }

  componentDidHide () { }

  chooseType (id) {
    if (this.state.activeType === id) return
    this.setState({
      activeType: id,
      foodList: data.toHome.foodList[id] || ''
    })
  }

  toDetail (foodId) {
    console.log(foodId)
    Taro.navigateTo({
      url:`/pages/foodDetail/foodDetail?id=${foodId}`
    })
  }

  render () {
    const showTopBar = process.env.TARO_ENV === 'h5'
    const slideHeight = process.env.TARO_ENV === 'h5' ? Taro.getSystemInfoSync().windowHeight - 150 : Taro.getSystemInfoSync().windowHeight-50 +'px'
    return (
      <View className='to_home' style={{minHeight: this.state.height }}>
        {showTopBar ? <TopBar text='食材到家' />: null}
        <Search></Search>
        <View className='content'>
          <View className='content_slide-left' style={{maxHeight: slideHeight}}>
            {
              this.state.foodTypeList && this.state.foodTypeList.map(item =>
                <View  key={item.id}   onClick={this.chooseType.bind(this, item.id)}  className={['slide_left-item', item.id === this.state.activeType ? 'active' : '']}>
                  <Text >{item.text}</Text>
                </View>
              )
            }
          </View>
          <View className='content_slide-right' style={{maxHeight: slideHeight}}>
            {
              this.state.foodList && this.state.foodList.map(item => (
                <View key={item.foodId} className='food_item'  onClick={this.toDetail.bind(this, item.foodId)} >
                  <View className='img_wrap'>
                    <Image className='taro-img' mode='scaleToFill' src={item.imgSrc}  />
                  </View>
                  <View className='food_text'>
                    {item.text}
                  </View>
                </View>
              ))
            }
          </View>

        </View>
      </View>
    )
  }
}

